<template>
  <view class="star-rating" @touchmove="handleTouchMove">
    <view
      v-for="index in maxRating"
      :key="index"
      class="star-item"
      :style="{ backgroundImage: `url('/static/images/star-${index <= rating ? 'full' : 'empty'}.png')` }"
      @click.stop="handleClick(index)"
    ></view>
  </view>
</template>

<script>
export default {
  props: {
    maxRating: {
      type: Number,
      default: 5
    },
    initialRating: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      rating: this.initialRating
    };
  },
  methods: {
    handleClick(index) {
      this.rating = index;
      this.$emit('ratingChanged', this.rating);
    },
    handleTouchMove(event) {
      event.preventDefault();
      const touch = event.touches[0];
      const rect = this.$el.getBoundingClientRect();
      const x = touch.clientX - rect.left;
      const starWidth = 24; // 根据实际情况调整
      let rating = Math.min(Math.floor(x / starWidth), this.maxRating);
      rating = rating > 0 ? rating : 1; // 确保至少选中一颗星
      this.rating = rating;
      this.$emit('ratingChanged', this.rating);
    }
  }
};
</script>

<style scoped>
.star-rating {
  display: flex;
  justify-content: space-between; /* 这会使星星之间的间隔均匀分布 */
  width: calc(24px * 5); /* 根据星星的数量和大小调整宽度 */
}
.star-item {
  width: 24px; /* 星星的宽度，根据实际情况调整 */
  height: 24px; /* 星星的高度，根据实际情况调整 */
  background-size: contain;
  background-repeat: no-repeat;
  cursor: pointer;
  margin: 0 2px; /* 减少星星之间的间隔 */
}
</style>